package com.aliang.shopping.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.aliang.shopping.common.PageResult;
import com.aliang.shopping.common.ResultCodeEnum;
import com.aliang.shopping.config.OssConfig;
import com.aliang.shopping.exception.DataException;
import com.aliang.shopping.exception.ServiceException;
import com.aliang.shopping.mapper.GoodsSpecMapper;
import com.aliang.shopping.mapper.OrdersInfoMapper;
import com.aliang.shopping.model.converter.CommonConverter;
import com.aliang.shopping.model.converter.GoodsConverter;
import com.aliang.shopping.model.dto.goods.GoodsEsDto;
import com.aliang.shopping.model.enums.OrdersStatusEnum;
import com.aliang.shopping.model.po.GoodsSpec;
import com.aliang.shopping.model.po.OrdersInfo;
import com.aliang.shopping.model.vo.address.AddressVO;
import com.aliang.shopping.model.vo.cart.CartVO;
import com.aliang.shopping.model.vo.orders.OrdersItemVO;
import com.aliang.shopping.model.vo.orders.OrdersVO;
import com.aliang.shopping.service.OrdersInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author ShiBaLover
 * @description 针对表【orders_info(订单信息表)】的数据库操作Service实现
 * @createDate 2025-01-04 22:07:32
 */
@Service
@AllArgsConstructor
public class OrdersInfoServiceImpl extends ServiceImpl<OrdersInfoMapper, OrdersInfo>
        implements OrdersInfoService {

    private final GoodsSpecMapper goodsSpecMapper;
    private final GoodsConverter goodsConverter;
    private final OssConfig ossConfig;
    private final CommonConverter<OrdersVO> commonConverter = new CommonConverter<>();

    @Override
    public PageResult<OrdersVO> getOrdersByBusinessId(Long businessId, Integer pageNum, Integer pageSize, Long ordersId, Integer status) {
        // 分页与实际不符，改为手动分页
        // 获取总条数
        Integer count = this.baseMapper.selectCount(new LambdaQueryWrapper<OrdersInfo>()
                .eq(OrdersInfo::getBusinessId, businessId) //商家Id
                .gt(OrdersInfo::getStatus, OrdersStatusEnum.WAIT_PAYMENT.getCode()) // 状态大于0
                .eq(Objects.nonNull(ordersId), OrdersInfo::getId, ordersId) //是否根据订单Id查询
                .eq(Objects.nonNull(status), OrdersInfo::getStatus, status) // 是否根据状态查询
        );
        //这条数为空，返回空对象。
        if (count == 0) {
            return new PageResult<OrdersVO>().empty();
        }
        //查询数据
        List<OrdersVO> records = this.baseMapper.getOrdersByBusinessId((pageNum - 1) * pageSize, pageSize, businessId, ordersId, status);
        List<List<OrdersItemVO>> collect = records.stream().map(OrdersVO::getOrdersItemVOS).collect(Collectors.toList());
        // 查询规格信息
        Map<Long, String> specMap = getSpecList(collect);
        //封装数据
        records.forEach(ordersFrontVO -> {
            // 手机号脱敏
            AddressVO address = ordersFrontVO.getAddress();
            String phone = DesensitizedUtil.mobilePhone(address.getPhone());
            address.setPhone(phone);
            // 处理订单列表数据
            List<OrdersItemVO> ordersItemVOS = ordersFrontVO.getOrdersItemVOS();
            ordersItemVOS.forEach(cartVO -> {
                if (StrUtil.isNotBlank(cartVO.getGoodsImage())) {
                    // 获取图片第一张
                    String oneMainImages = goodsConverter.getOneMainImages(cartVO.getGoodsImage());
                    if (StrUtil.isNotBlank(oneMainImages))
                        //设置完成路径
                        cartVO.setGoodsImage(ossConfig.getUrl() + oneMainImages);
                }
                String goodsSpecName = cartVO.getGoodsSpecName();
                List<Long> specList = JSONUtil.toList(goodsSpecName, Long.class);
                // 拼接规格名称
                List<String> specStrList = specList.stream().map(specMap::get).collect(Collectors.toList());
                String join = CollectionUtil.join(specStrList, ",");
                cartVO.setGoodsSpecName(join);
            });
        });

        return new PageResult<>(Long.valueOf(count), records);
    }


    /**
     * 获取规格信息
     *
     * @param voList
     * @return
     */
    private Map<Long, String> getSpecList(List<List<OrdersItemVO>> voList) {
        //获取规格Id
        Set<Long> specList = new HashSet<>();
        voList.forEach(cartVO -> {
            cartVO.forEach(cart -> {
                List<Long> list = JSONUtil.toList(cart.getGoodsSpecName(), Long.class);
                specList.addAll(list);
            });
        });
        if (specList.isEmpty()) throw new DataException(ResultCodeEnum.SPEC_IS_NOT_EXIT);
        // 查询规格信息
        return this.goodsSpecMapper.selectList(
                new LambdaQueryWrapper<GoodsSpec>()
                        .select(GoodsSpec::getId, GoodsSpec::getSpecName)
                        .in(GoodsSpec::getId, specList)
        ).stream().collect(Collectors.toMap(GoodsSpec::getId, GoodsSpec::getSpecName));
    }

    @Override
    public Map<Long, Integer> getSaleNumByGoodsId(List<Long> goodsIds) {
        //获取状态数据
        List<Integer> statusNums = Arrays.asList(OrdersStatusEnum.WAIT_EVALUATE.getCode(), OrdersStatusEnum.FINISH.getCode());
        List<GoodsEsDto> saleNums = this.baseMapper.querySaleNumByGoodsId(goodsIds, statusNums);
        // 如果数据为空，返回空
        if (saleNums.isEmpty()) return new HashMap<>();
        return saleNums.stream().collect(Collectors.toMap(GoodsEsDto::getId, GoodsEsDto::getSaleNum));
    }

    @Override
    public CartVO getPayNoByItemId(Long ordersItemId) {
        return this.baseMapper.getPayNoByItemId(ordersItemId);
    }

    @Override
    public Boolean cancelOrdersByIdWithUserId(Long orderId, Long userId) {
        // 获取订单信息的状态
        OrdersInfo ordersInfo = this.baseMapper.selectOne(new LambdaQueryWrapper<OrdersInfo>()
                .select(OrdersInfo::getId, OrdersInfo::getStatus)
                .eq(OrdersInfo::getId, orderId)
                .eq(OrdersInfo::getUserId, userId)
        );
        if (Objects.isNull(ordersInfo)) {
            throw new DataException(ResultCodeEnum.ORDERS_NOT_EXIT);
        }
        // 只有待支付的订单才能取消
        if (OrdersStatusEnum.WAIT_PAYMENT.getCode().equals(ordersInfo.getStatus())) {
            throw new ServiceException(ResultCodeEnum.ORDERS_CANCEL_BAD);
        }
        // 状态为待付款，则修改状态为已取消
        ordersInfo.setStatus(OrdersStatusEnum.CANCELLED.getCode());
        this.baseMapper.updateById(ordersInfo);
        return true;
    }
}




